<?php

namespace app\admin\controller\qingdong\general;

use addons\qingdong\model\FormField;
use app\admin\controller\qingdong\Base;
use addons\qingdong\model\Field;
use think\Db;
use think\Exception;

/**
 * 字段管理
 */
class Form extends Base {
	protected $relationSearch = true;
	/**
	 * @var \addons\qingdong\model\Form
	 */
	protected $model       = null;


	public function _initialize() {
		parent::_initialize();
		$this->model =new \addons\qingdong\model\Form;
	}


	/**
	 * 查看
	 */
	public function index() {
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if ($this->request->isAjax()) {

			$forms = $this->model->where([])->select();
			$forms = collection($forms)->toArray();
			if (empty($forms)) {
				$insertALl = $this->model->field('name,type,data')->select();
				$insertALl = collection($insertALl)->toArray();
				foreach ($insertALl as $k => $item) {
					$item['createtime'] = time();
					$item['updatetime'] = time();
					$insertALl[$k]      = $item;
				}
				$this->model->insertAll($insertALl);
				$forms = $this->model->select();
				$forms = collection($forms)->toArray();
			}


			$result = array("total" => count($forms), "rows" => $forms);

			return json($result);
		}

		return $this->view->fetch();
	}


    /**
     * 修改字段
     */
	public function edit($ids = null) {
        if ($this->request->isPost()) {
            $id = input('id');
            $data = input('data');
            if (empty($id) || empty($data)) {
                $this->error('参数错误');
            }
            $row = $this->model->where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('表单不存在');
            }
            Db::startTrans();
            try {
                $result=$this->model->updateForm($id, $data);
                if($result === false){
                    throw new Exception('修改表单失败');
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('设置成功');
        }
		$basefile = request()->baseFile();

		$this->assign("basefile", $basefile);
		$this->assign("token", $this->request->token());

		$this->view->engine->layout(false);

		return $this->view->fetch();
	}

    /**
     * 获取模板详情
     */
	public function getinfo() {
		$id = input('id');
		if (empty($id)) {
			$this->error('参数不存在');
		}
		$find = $this->model->where(['id' => $id])->find();

		$this->success('请求成功', '', $find);
	}
}
